package com.example.electricbicycle.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import com.example.electricbicycle.dao.VehicleStockDaoImpl;

@WebServlet("/DeleteStockServlet")
public class DeleteStockServlet extends HttpServlet {

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String idStr = req.getParameter("id");
        int id;

        try {
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            sendRedirectWithMessage(req, resp, "error", "请输入有效的数字ID");
            return;
        }

        VehicleStockDaoImpl stockDao = new VehicleStockDaoImpl();
        boolean success;
        try {
            success = stockDao.deleteStock(id);

            if (success) {
                sendRedirectWithMessage(req, resp, "success", "删除成功");
            } else {
                sendRedirectWithMessage(req, resp, "error", "未找到对应库存记录");
            }
        } catch (SQLException e) {
            sendRedirectWithMessage(req, resp, "error", "数据库错误: " + e.getMessage());
        }
    }

    private void sendRedirectWithMessage(HttpServletRequest req,
                                         HttpServletResponse resp,
                                         String type,
                                         String message) throws IOException {
        String param = type + "Msg=" + URLEncoder.encode(message, "UTF-8");
        resp.sendRedirect("/web/StockQueryServlet?" + param);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendRedirect("/warehouse/deleteStock.jsp");
    }
}